package com.ks.app.admin.service.impl;

import java.io.File;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.Query;
import org.springframework.stereotype.Service;
import com.ks.app.admin.hibernate.KsOperaterLog;
import com.ks.app.admin.hibernate.KsVersion;
import com.ks.app.admin.service.KsVersionService;
import com.ks.app.admin.service.KsoperatelogService;
import com.ks.app.admin.service.impl.BaseServiceImpl;
import com.ks.app.admin.util.Pager;

@Service("ksVersionService")
public class KsVersionServiceImpl extends BaseServiceImpl implements KsVersionService{

	@Resource
	private KsoperatelogService ksoperatelogService;
	
	
	/**
	 * 通过版本类别和分辨率获取当前版本
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String findVersion(int vtype, int status) {
		
		String hql = "from KsVersion v where v.vtype="+vtype+" and v.status="+status+" order by v.id desc";

		List<KsVersion> list = em.createQuery(hql).getResultList();
		
		KsVersion kv = null;
		if(list != null && list.size()>0){
			kv = list.get(0);
		}
		return kv==null?"0":kv.getVersion();
	}

	/**
	 * 更新分辨率
	 */
	@Override
	public void uploadVersion(int vtype, String resolution, long version) {
		
		String hql ="update KsVersion v set v.version="+version+" where v.vtype="+vtype+" and v.resolution='"+resolution+"'";
		
		em.createQuery(hql).executeUpdate();
	}
	
	
	
	//添加版本
	public long addKsVersion(KsVersion KsVersion,String username) 
	{
		try
		{			
			//添加日志
			em.persist(KsVersion);		
			
			KsOperaterLog ksOperateLog =new KsOperaterLog();
			ksOperateLog.setContent(username+"添加了版本:[id="+KsVersion.getId()+"];[类型="+KsVersion.getVtype()+"];[版本号="+KsVersion.getVersion()+"];");
			ksOperateLog.setLogtime(new Date());
			ksOperateLog.setOperater(username);
			ksOperateLog.setLogtype(1);
			ksOperateLog.setStatus(2);
			ksOperateLog.setOpename("添加版本");
			ksoperatelogService.save(ksOperateLog);
			
			return KsVersion.getId();
		}
		catch(Exception ee)
		{  
			ee.printStackTrace();
			return 0;
		}
	}
	
	//取得最新的 有效的版本号
	public long getversionId(int vtype, String resolution,int status)
	{
		try {
			String sql = " from KsVersion  where 1=1 ";		
			if(vtype>0)
			{
				sql=sql+" and vtype='"+vtype+"' ";	
			}		
			else 
			{return -1;}
			if(resolution!=null&&resolution.length()>0)
			{
				sql=sql+" and resolution ='"+resolution+"' ";	
			}
			if(status>=0)
			{
				sql=sql+" and status='"+status+"' ";	
			}	
			else
				{return -1;}
			Query query = em.createQuery(sql+" order by id desc ");
			   
			@SuppressWarnings("unchecked")
			List <KsVersion> list = query.getResultList();	
			if(list.size()>0)
			{
				return Long.parseLong(list.get(0).getVersion());
			}		
			else {return 0;}
		}
		catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}
	
	
	//取得最新的 有效的版本记录
	public KsVersion getversion(int vtype, String resolution,int status)
	{
		try {
			
			String sql = " from KsVersion  where 1=1 ";		
			if(vtype>0)
			{
				sql=sql+" and vtype='"+vtype+"' ";	
			}		
			else 
			{return null;}
			if(resolution!=null&&resolution.length()>0)
			{
				sql=sql+" and resolution ='"+resolution+"' ";	
			}
			if(status>0)
			{
				sql=sql+" and status='"+status+"' ";	
			}	
			else
				{return null;}
			Query query = em.createQuery(sql+" order by id desc ");
			
			
			
			@SuppressWarnings("unchecked")
			List <KsVersion> list = query.getResultList();	
			if(list != null && list.size()>0)
			{
				return list.get(0);
			}		
			else {return null;}
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	//删除版本
	public long deleteKsVersion(String uiid,String username)
	{
		try
		{			
			if(uiid!=null&&uiid.length()>0)
			{
				String sql = " from KsVersion where id=? ";	
				Query query = em.createQuery(sql);			
				long m_iid=Long.parseLong(uiid);
				query.setParameter(1,m_iid);			
				@SuppressWarnings("unchecked")
				List <KsVersion> list = query.getResultList();		
				if(list.size()>0)
				{					
					String getFilepath=list.get(0).getFilepath();
					String getVersion=list.get(0).getVersion();
					long getVtype=list.get(0).getVtype();
					long uid=list.get(0).getId();
					
					em.remove(list.get(0));	
					
					KsOperaterLog ksOperateLog =new KsOperaterLog();
					ksOperateLog.setContent(username+"删除了版本:[id="+uid+"];[path="+getFilepath+"];[版本号="+getVersion+"];[类型="+getVtype+"];");
					ksOperateLog.setLogtime(new Date());
					ksOperateLog.setOperater(username);
					ksOperateLog.setLogtype(1);
					ksOperateLog.setStatus(2);
					ksOperateLog.setOpename("删除版本");
					ksoperatelogService.save(ksOperateLog);
					return 1;
				}
			}	
			return 0;
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
			return 0;
		}
	}
	
	
	//根据条件获得版本记录
	public List<KsVersion> GetKsVersionList(int vtype,String uiid,String sd,String ed,String isshow, Pager pager)
	{
		String sql = " from KsVersion where 1=1 ";	
		if(vtype>=0)
		{
			sql=sql+"  and vtype='"+vtype+"'";	
		}	
		if(uiid!=null&&uiid.length()>0&&Long.parseLong(uiid)>0)
		{
			sql=sql+"  and version='"+uiid+"'";	
		}	
		
		if(sd!=null&&sd.length()>0)
		{
			sql=sql+"  and createtime>='"+sd+"'";	
		}	
		if(ed!=null&&ed.length()>0)
		{
			sql=sql+"  and createtime<='"+ed+"'";	
		}
		if(isshow!=null&&isshow.length()>0&&Long.parseLong(isshow)>=0)
		{
			sql=sql+"  and status='"+isshow+"' ";	
		}
		Query query = em.createQuery(sql+" order by id desc ");
	
		query.setMaxResults(pager.getCntOfPage()) ;
	    query.setFirstResult( (pager.getCurPage()-1) * pager.getCntOfPage() );
	    pager.setTotoalCnt(GetcntKsApk(vtype,uiid,sd, ed, isshow));
		@SuppressWarnings("unchecked")
		List <KsVersion> list = query.getResultList();	
		return list;
	}
	
	
	public int GetcntKsApk(int vtype,String uiid,String sd,String ed,String isshow)
	{
		String sql = " select count(*) from KsVersion where 1=1 ";	
		if(vtype>=0)
		{
			sql=sql+"  and vtype='"+vtype+"'";	
		}	
		if(uiid!=null&&uiid.length()>0&&Long.parseLong(uiid)>0)
		{
			sql=sql+"  and version='"+uiid+"'";	
		}	
		
		if(sd!=null&&sd.length()>0)
		{
			sql=sql+"  and createtime>='"+sd+"'";	
		}	
		if(ed!=null&&ed.length()>0)
		{
			sql=sql+"  and createtime<='"+ed+"'";	
		}
		if(isshow!=null&&isshow.length()>0&&Long.parseLong(isshow)>=0)
		{
			sql=sql+"  and status='"+isshow+"' ";	
		}
		Query query = em.createQuery(sql);
		
		return Integer.parseInt(String.valueOf(query.getSingleResult()));
	}

	@SuppressWarnings("unchecked")
	public String isexsistVersion(String vtype,String resolution,String version)
	{
		String sql = " from KsVersion where 1=1 ";	
		if(vtype!=null&&vtype.trim().length()>0&&Long.parseLong(vtype)>0)
		{
			sql=sql+"  and vtype='"+vtype+"'";	
		}	
		else return "";
		if(version!=null&&version.trim().length()>0&&Long.parseLong(version)>0)
		{
			sql=sql+"  and version='"+version+"'";	
		}		else return "";
		if(resolution!=null&&resolution.trim().length()>0)
		{
			sql=sql+"  and resolution='"+resolution+"'";	
		}
		Query query = em.createQuery(sql+" order by id desc ");
		List <KsVersion> list = query.getResultList();	
		if(list!=null&&list.size()>0)
		{
			return "Y";
		}
		return "";
	}
	
	
	public String getApkfilepath(String versionid,String isforce)
	{		
		try {			
			KsVersion kv=getversion(1,"",2);
			if(kv==null){return "";}//没有最新的版本记录 无法下载
			String verid=kv.getVersion().replace(".","").trim();			
			String adidlist=kv.getFilepath();
			if(isforce.equals("1")||Long.parseLong(versionid.replace(".","").trim())<Long.parseLong(verid))//强制下载或者传入的版本低于最新版本
			{						
				return adidlist;
			}
			return "";			
		} 
		catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	
	/**
     * 判断文件及目录是否存在，若不存在则创建文件及目录
     * @param filepath
     * @return
     * @throws Exception
     */
	public static File checkExist(String filepath) throws Exception{
       File file=new File(filepath);
      
       if (file.exists()) {//判断文件目录的存在
           if(file.isDirectory()){//判断文件的存在性      
             }else{
              file.createNewFile();//创建文件
             }
       }else {
           File file2=new File(file.getParent());
           file2.mkdirs();
           if(file.isDirectory()){      
             }else{      
              file.createNewFile();//创建文件 
             }
       }
       return file;
    }


	/**
	 * 分页获取版本列表数据
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<KsVersion> findKsVersionList(int vtype, int status, Pager pager) {
		
		String sql  = " from KsVersion where 1=1 ";
		String csql = " select count(*) from KsVersion where 1=1";
		
		if (vtype != 0) {
			sql  = sql + "  and vtype="+vtype;
			csql = csql + "  and vtype="+vtype;
		}
		
		if(status != 0){
			sql  = sql +" and status="+status;
			csql = csql +" and status="+status;
		}
		
		sql  = sql +" order by id desc";
	
		Query query = em.createQuery(sql);
		Query cquery = em.createQuery(csql);
		
		query.setMaxResults(pager.getCntOfPage());
		query.setFirstResult((pager.getCurPage() - 1) * pager.getCntOfPage());
		pager.setTotoalCnt(Integer.parseInt(String.valueOf(cquery.getSingleResult())));
		
		return query.getResultList();
	} 
}
